﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using MedicalCare.DbLayer.Adaptors;
using MedicalCare.EntityDefinitions.Entities;
using MedicalCare.Messages;
using StructureMap;
using System.IO;
using System.Web;
using MedicalCare.Common;

namespace MedicalCare
{
    public partial class NurseSchedule : System.Web.UI.Page
    {
        private const int ChooseDefaultId = 0;
        private IList<ScheduleStatusEntity> scheduleStatusList;

        private IList<FamilyEquipmentEntity> familyEquipmentList
        {
            get
            {
                return (List<FamilyEquipmentEntity>)(ViewState["familyEquipmentList"]);
            }
            set { ViewState["familyEquipmentList"] = value; }
        }

        private IList<EquipmentTypeEntity> equipmentTypeList
        {
            get
            {
                return (List<EquipmentTypeEntity>)(ViewState["equipmentTypeList"]);
            }
            set { ViewState["equipmentTypeList"] = value; }
        }

        private IList<DateTime> bookedDateList
        {
            get
            {
                return (List<DateTime>)(ViewState["bookedDateList"]);
            }
            set { ViewState["bookedDateList"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CalendarSchedule.SelectedDate = DateTime.Today;
                InitialCalendar();
                InitialSchedule();
                InitialScheduleStatus();
                GetAllEquipmentsType();
            }
        }

        private void ShowScheduleListControl()
        {
            ScheduleList.Visible = true;
        }

        private void HiddenScheduleListControl()
        {
            ScheduleList.Visible = false;
        }

        private void ShowScheduleDetailsControl()
        {
            panelScheduleDetails.Visible = true;
            panelComments.Visible = true;
            panelCommentSumit.Visible = true;
        }

        private void HiddenScheduleDetailsControl()
        {
            panelScheduleDetails.Visible = false;
            panelComments.Visible = false;
            panelCommentSumit.Visible = false;
        }

        private void InitialCalendar()
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();

            bookedDateList = scheduleAdaptor.GetAllBookedDatebyNurseId(AppPage.CurrentUser.Id);
            // test
            //bookedDateList = scheduleAdaptor.GetAllBookedDatebyNurseId(16);
        }

        protected void CalendarSchedule_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
        {
            if (e.Day.IsOtherMonth)
            {
                e.Cell.Controls.Clear();
            }
            else
            {
                foreach (DateTime dt in bookedDateList)
                {
                    if (e.Day.Date.Subtract(dt).Days == 0)
                    {
                        e.Cell.BackColor = System.Drawing.Color.Green; //高亮显示的日期，背景色为红色。
                    }
                }
            }
        }

        protected void CalendarSchedule_SelectionChanged(object sender, EventArgs e)
        {
            HiddenScheduleDetailsControl();

            InitialSchedule();
        }

        private void InitialSchedule()
        {
            var message = new ScheduleMessage()
            {
                Date = CalendarSchedule.SelectedDate.Date,
                NurseId = AppPage.CurrentUser.Id
            };
            var scheduleList = CheckSchedule(message);
            if (scheduleList.Count > 0)
            {
                // 显示已存在的schedule
                ShowScheduleListControl();
                var objPds = new PagedDataSource { DataSource = scheduleList };
                ScheduleList.DataSource = objPds;
                ScheduleList.DataBind();
            }else
            {
                HiddenScheduleListControl();
            }
        }

        private IList<ScheduleEntity> CheckSchedule(ScheduleMessage message)
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();

            var orderKey = " sche.StartDT ";
            var orderValue = " ASC ";
            var _whereString = " sche.ScheduleDay = '" + message.Date + "' AND sche.NurseId = " + message.NurseId;
            var scheduleEntityList = scheduleAdaptor.GetSchedule(orderKey, orderValue, _whereString);
            return scheduleEntityList;
        }

        private void InitialScheduleStatus()
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();
            scheduleStatusList = scheduleAdaptor.GetScheduleStatus();
            scheduleStatusList.Add(new ScheduleStatusEntity() { Name = "请选择", Code = "" });

            ddlScheduleStatus.DataTextField = "Name";
            ddlScheduleStatus.DataValueField = "Code";
            ddlScheduleStatus.DataSource = scheduleStatusList;
            ddlScheduleStatus.DataBind();
        }

        private void GetAllEquipmentsType()
        {
            var equipmentTypeAdaptor = ObjectFactory.GetInstance<IEquipmentTypeAdaptor>();
            equipmentTypeList = equipmentTypeAdaptor.GetAllEquipmentType();
            equipmentTypeList.Add(new EquipmentTypeEntity() { Name = "请选择", Id = ChooseDefaultId });
        }

        // UI control
        protected object ToTime(object obj)
        {
            if (obj != null)
            {
                var date = DateTime.Parse(obj.ToString());
                return date.ToString("HH:mm");
            }
            return string.Empty;
        }

        protected void ScheduleList_ItemCommand(object source, DataListCommandEventArgs e)
        {
            try
            {
                var scheduleId = Convert.ToInt32(e.CommandArgument);
                switch (e.CommandName.ToUpper())
                {
                    case "VIEW":
                        InitialScheduleDetails(scheduleId);
                        InitialComments(scheduleId);
                        break;
                    default:
                        break;
                }
            }
            catch
            {

            }
        }

        protected void ScheduleList_ItemDataBound(object sender, DataListItemEventArgs e)
        {

        }

        private ScheduleEntity GetScheduleDetails(int scheduleId)
        {
            ShowScheduleDetailsControl();

            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();

            var orderKey = " sche.StartDT ";
            var orderValue = " ASC ";
            var whereString = " sche.Id = " + scheduleId;
            var scheduleDetails =  scheduleAdaptor.GetSchedule(orderKey, orderValue, whereString)[0];
            var tempfamilyEquipmentsList = scheduleAdaptor.GetEquipementsByScheduleId(scheduleId);
            
            scheduleDetails.FamilyEquipmentsList = tempfamilyEquipmentsList;
            return scheduleDetails;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();

            var scheduleMsg = new ScheduleMessage()
                          {
                              Id = int.Parse(hiddenScheduleId.Value),
                              Status = ddlScheduleStatus.SelectedValue,
                          };
            scheduleAdaptor.UpdateScheduleStatus(scheduleMsg);

            // get all equipement
            var equipFamilyMsgList = new List<EquipmentFamilyMappingMessage>();
            var equipmentAdaptor = ObjectFactory.GetInstance<IEquipmentsAdaptor>();
            foreach (var item in repeaterEquipments.Items)
            {
                var ddlEquipmentsType = (DropDownList)((RepeaterItem)item).FindControl("ddlEquipmentsType");
                var equipmentTypeId = int.Parse(ddlEquipmentsType.SelectedValue);
                if (equipmentTypeId > 0)
                {
                    var tbEquipmentSensorId = (TextBox)((RepeaterItem)item).FindControl("tbEquipmentSensorId");
                    var equipMsg = new EquipmentsMessage()
                                       {
                                           SensorId = tbEquipmentSensorId.Text,
                                           EquipmentTypeId = equipmentTypeId
                                       };
                    var equipInfo = equipmentAdaptor.GetEquipmentBySensorId(equipMsg);
                    if(equipInfo!=null)
                    {
                        equipFamilyMsgList.Add(new EquipmentFamilyMappingMessage()
                                                   {
                                                        CreateUser = AppPage.CurrentUser.UserName,
                                                        FamilyId = AppPage.CurrentUser.Id,
                                                        EquipmentId = equipInfo.Id,
                                                        ScheduleId = scheduleMsg.Id
                                                   });
                    }
                }
            }

            scheduleAdaptor.UpdateFamilyEquipments(equipFamilyMsgList);
        }

        protected void repeaterEquipments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var lbEquipmentTypeId = (Label) (e).Item.FindControl("lbEquipmentTypeId");
            var ddlEquipmentsType = (DropDownList)e.Item.FindControl("ddlEquipmentsType");
            var tbEquipmentSensorId = (TextBox)e.Item.FindControl("tbEquipmentSensorId");
            var btnRemoveEquipment = (Button)e.Item.FindControl("btnRemoveEquipment");

            ddlEquipmentsType.DataSource = equipmentTypeList;
            ddlEquipmentsType.DataBind();

            if (CalendarSchedule.SelectedDate.Date < DateTime.Now.Date) //select view history days,need to hide equipments,schedule status 
            {
                lbEquipmentTypeId.Enabled = false;
                ddlEquipmentsType.Enabled = false;
                tbEquipmentSensorId.Enabled = false;

                lbtnAddEquipement.Visible = false;//添加设备link
                btnRemoveEquipment.Visible = false;//equipment delete button

                ddlScheduleStatus.Enabled = false;
                btnSave.Visible = false;
            }
            else
            {
                if (int.Parse(lbEquipmentTypeId.Text) > 0)
                {
                    ddlEquipmentsType.SelectedValue = lbEquipmentTypeId.Text;
                    ddlEquipmentsType.Enabled = false;
                    tbEquipmentSensorId.Enabled = false;
                }
                else
                {
                    ddlEquipmentsType.SelectedValue = ChooseDefaultId.ToString();
                }

            }

        }

        protected void lbtnAddEquipement_Click(object sender, EventArgs e)
        {
            getCurrentEquipmentsData();
            var newIndex = default(int);
            if(familyEquipmentList.Count>0)
                newIndex = familyEquipmentList[familyEquipmentList.Count -1].Index + 1;
            familyEquipmentList.Add(new FamilyEquipmentEntity()
                                        {
                                            Index = newIndex,
                                            ScheduleId = int.Parse(hiddenScheduleId.Value),
                                        });
            repeaterEquipments.DataSource = familyEquipmentList;
            repeaterEquipments.DataBind();
        }

        protected void repeaterEquipments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                var index = Convert.ToInt32(e.CommandArgument);
                switch (e.CommandName.ToUpper())
                {
                    case "REMOVE":
                        removeEquipmentItembyIndex(index);
                        repeaterEquipments.DataSource = familyEquipmentList;
                        repeaterEquipments.DataBind();
                        break;
                    default:
                        break;
                }
            }
            catch
            {

            }
        }

        private void getCurrentEquipmentsData()
        {
            var tempFamilyEquipmentList = new List<FamilyEquipmentEntity>();
            foreach (var item in repeaterEquipments.Items)
            {
                var ddlEquipmentsType = (DropDownList)((RepeaterItem)item).FindControl("ddlEquipmentsType");
                var tbEquipmentSensorId = (TextBox)((RepeaterItem)item).FindControl("tbEquipmentSensorId");
                var equipmentTypeId = int.Parse(ddlEquipmentsType.SelectedValue);
                var equipmentSensorId = tbEquipmentSensorId.Text;

                if (equipmentTypeId > 0 && !string.IsNullOrEmpty(equipmentSensorId))
                {
                    tempFamilyEquipmentList.Add(new FamilyEquipmentEntity()
                                                    {
                                                        EquipmentTypeId = equipmentTypeId,
                                                        EquipmentSensorId = equipmentSensorId
                                                    }); 
                }
            }

            familyEquipmentList = tempFamilyEquipmentList;
        }

        private void removeEquipmentItembyIndex(int index)
        {
            var deleteOject = new FamilyEquipmentEntity();
            foreach (var item in familyEquipmentList)
            {
                if (item.Index == index)
                {
                    deleteOject = item;
                    break;
                }
            }
            familyEquipmentList.Remove(deleteOject);
        }

        #region schedule Details
        private void InitialScheduleDetails(int scheduleId)
        {
            var schedule = GetScheduleDetails(scheduleId);
            hiddenScheduleId.Value = schedule.Id.ToString();
            lbDamilyName.Text = schedule.FamilyName;//病人姓名

            ddlScheduleStatus.SelectedValue = schedule.Status;

            //initial equipments
            familyEquipmentList = schedule.FamilyEquipmentsList;
            repeaterEquipments.DataSource = familyEquipmentList;
            repeaterEquipments.DataBind();
        }
        #endregion


        #region Schdeule Comments
        private void InitialComments(int scheduleId)
        {
            var scheduleCommentsMsg = new ScheduleCommentMessage()
                                          {
                                              ScheduleId = scheduleId
                                          };
            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();
            var scheduleCommentsList = scheduleAdaptor.GetCommentsByScheduleId(scheduleCommentsMsg);
            repeaterComments.DataSource = scheduleCommentsList;
            repeaterComments.DataBind();
            if (scheduleCommentsList == null || scheduleCommentsList.Count == 0) //hide the panel names "panelComments"
            {
                panelComments.Visible = false;
            }
        }


        protected void btnAddComment_Click(object sender, EventArgs e)
        {
            #region 保存图片和视频文件
            upload upImageFiles = new upload() { FileType = "jpg|gif|bmp|jpeg|png", Path = "\\UploadFile", Sizes = 200 };//200Kb

            upload upVedioFiles = new upload() { FileType = "wma|rmvb|rm", Path = "\\UploadFile", Sizes = 100 * 1000 };//100M
            
            string picSavedPath=null;
            string vedioSavePath = null;
            if(!string.IsNullOrEmpty(uploadPic.PostedFile.FileName))
            {
                picSavedPath = upImageFiles.SaveAs(uploadPic.PostedFile).ToString();
            }
            if (!string.IsNullOrEmpty(uploadVedio.PostedFile.FileName))
            {
                vedioSavePath = upVedioFiles.SaveAs(uploadVedio.PostedFile).ToString();
            }

            if (picSavedPath=="" || vedioSavePath=="")
            {
                //显示错误提示在前台
                lblMessage.Text = upImageFiles.saveFileErrorMessage + " " + upVedioFiles.saveFileErrorMessage;
                return;//返回不执行后面的保存逻辑
            }
            #endregion

            var scheduleAdaptor = ObjectFactory.GetInstance<IScheduleAdaptor>();
            var scheduleId = int.Parse(hiddenScheduleId.Value);
            var comment = tbCommment.Text;
            if (!string.IsNullOrEmpty(comment))
            {
                var scheduleCommentMsg = new ScheduleCommentMessage()
                                             {
                                                 Comment = tbCommment.Text,
                                                 UserId = AppPage.CurrentUser.Id,
                                                 ScheduleId = scheduleId,
                                                 ImagePath = picSavedPath,
                                                 VedioPath= vedioSavePath
                                             };
                scheduleAdaptor.UpdateComments(scheduleCommentMsg);

                InitialComments(scheduleId);
            }
        }
        #endregion
    }

}